<?php
/**
 * 云盘系统主页面
 */

require_once 'config/config.php';
require_once 'includes/db.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    header('Location: install.php');
    exit;
}

// 处理登出
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

$message = '';
$messageType = '';

// 只有管理员登录后才能看到文件列表
$isLoggedIn = $_SESSION['admin_logged_in'] ?? false;

if ($isLoggedIn) {
    // 获取文件列表
    try {
        $db = new Database();
        $files = $db->fetchAll("SELECT * FROM files ORDER BY upload_time DESC");
    } catch (Exception $e) {
        $message = '加载文件列表失败: ' . $e->getMessage();
        $messageType = 'error';
    }
} else {
    $files = [];
}

/**
 * 格式化文件大小
 */
function formatFileSize($bytes) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= (1 << (10 * $pow));
    return round($bytes, 2) . ' ' . $units[$pow];
}

/**
 * 获取文件图标
 */
function getFileIcon($ext) {
    $icons = [
        'pdf' => '📄', 'doc' => '📝', 'docx' => '📝', 'txt' => '📃',
        'jpg' => '🖼️', 'jpeg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️',
        'zip' => '🗜️', 'rar' => '🗜️', '7z' => '🗜️',
        'mp4' => '🎬', 'avi' => '🎬', 'mov' => '🎬',
        'mp3' => '🎵', 'wav' => '🎵', 'flac' => '🎵',
        'xls' => '📊', 'xlsx' => '📊', 'ppt' => '📽️', 'pptx' => '📽️'
    ];
    return $icons[strtolower($ext)] ?? '📦';
}

/**
 * 获取直链
 */
function getDirectLink($link) {
    if (empty($link)) {
        return '';
    }
    $protocol = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http';
    return $protocol . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/direct.php?link=' . $link;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= SITE_NAME ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f5f7;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header-left h1 {
            color: #333;
            font-size: 32px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-left p {
            color: #666;
            font-size: 14px;
        }

        .header-right {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .admin-badge {
            background: #007AFF;
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
        }

        .btn {
            padding: 10px 24px;
            background: #007AFF;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
            background: #0056CC;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }

        .btn-danger {
            background: #FF3B30;
            box-shadow: 0 2px 8px rgba(255, 59, 48, 0.2);
        }

        .btn-danger:hover {
            background: #D70015;
            box-shadow: 0 4px 16px rgba(255, 59, 48, 0.3);
        }

        .btn-success {
            background: #34C759;
            box-shadow: 0 2px 8px rgba(52, 199, 89, 0.2);
        }

        .btn-success:hover {
            background: #248A3D;
            box-shadow: 0 4px 16px rgba(52, 199, 89, 0.3);
        }

        .btn-info {
            background: #FF9500;
            box-shadow: 0 2px 8px rgba(255, 149, 0, 0.2);
        }

        .btn-info:hover {
            background: #CC7700;
            box-shadow: 0 4px 16px rgba(255, 149, 0, 0.3);
        }

        .login-panel {
            background: white;
            border-radius: 20px;
            padding: 40px;
            box-shadow: 0 8px 40px rgba(0,0,0,0.08);
            max-width: 400px;
            margin: 100px auto;
            text-align: center;
        }

        .login-icon {
            font-size: 64px;
            margin-bottom: 20px;
        }

        .login-title {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
        }

        .login-subtitle {
            color: #666;
            margin-bottom: 30px;
        }

        .upload-area {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 30px;
        }

        .upload-box {
            border: 2px dashed #D1D1D6;
            border-radius: 16px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
        }

        .upload-box:hover {
            border-color: #007AFF;
            background: #F2F2F7;
        }

        .upload-box.dragover {
            border-color: #007AFF;
            background: #E3F2FD;
        }

        .upload-icon {
            font-size: 48px;
            margin-bottom: 16px;
        }

        .upload-text {
            color: #666;
            font-size: 16px;
            margin-bottom: 8px;
        }

        .upload-hint {
            color: #999;
            font-size: 14px;
        }

        #file-input {
            display: none;
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e0e0e0;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 12px;
            display: none;
        }

        .progress-fill {
            height: 100%;
            background: #007AFF;
            transition: width 0.3s;
            width: 0%;
        }

        .files-list {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        }

        .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .list-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
        }

        .files-grid {
            display: grid;
            gap: 16px;
        }

        .file-item {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px;
            background: #F2F2F7;
            border-radius: 12px;
            transition: all 0.3s;
        }

        .file-item:hover {
            background: #E8E8ED;
            transform: translateX(4px);
        }

        .file-icon {
            font-size: 32px;
            width: 48px;
            text-align: center;
        }

        .file-info {
            flex: 1;
            min-width: 0;
        }

        .file-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;
            word-break: break-all;
        }

        .file-meta {
            display: flex;
            gap: 16px;
            font-size: 12px;
            color: #999;
        }

        .file-direct-link {
            margin-top: 8px;
            padding: 8px 12px;
            background: white;
            border-radius: 6px;
            font-size: 12px;
            color: #666;
            word-break: break-all;
        }

        .file-direct-link a {
            color: #667eea;
            text-decoration: none;
            word-break: break-all;
        }

        .file-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state-icon {
            font-size: 64px;
            margin-bottom: 16px;
        }

        .empty-state-text {
            font-size: 16px;
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 16px 24px;
            border-radius: 8px;
            color: white;
            font-weight: 500;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
            transform: translateX(400px);
            transition: transform 0.3s;
        }

        .toast.show {
            transform: translateX(0);
        }

        .toast.success {
            background: #34C759;
        }

        .toast.error {
            background: #FF3B30;
        }

        .copy-btn {
            background: #f0f0f0;
            color: #666;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            cursor: pointer;
            margin-left: 8px;
            transition: all 0.2s;
        }

        .copy-btn:hover {
            background: #007AFF;
            color: white;
        }

        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 20px;
            }

            .header-right {
                width: 100%;
                justify-content: flex-end;
            }

            .file-item {
                flex-direction: column;
                align-items: flex-start;
            }

            .file-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }
    </style>
</head>
<body>
    <div class="toast" id="toast"></div>

    <div class="container">
        <?php if (!$isLoggedIn): ?>
            <!-- 未登录状态：显示登录面板 -->
            <div class="login-panel">
                <div class="login-icon">🔐</div>
                <h2 class="login-title">管理员登录</h2>
                <p class="login-subtitle">请登录以管理您的文件</p>
                <a href="login.php" class="btn" style="width: 100%; justify-content: center;">立即登录</a>
            </div>
        <?php else: ?>
            <!-- 已登录状态：显示完整界面 -->
            <div class="header">
                <div class="header-left">
                    <h1>☁️ <?= SITE_NAME ?></h1>
                    <p>简单、安全、高效的文件存储系统</p>
                </div>
                <div class="header-right">
                    <span class="admin-badge">👤 <?= htmlspecialchars($_SESSION['admin_username']) ?></span>
                    <a href="?logout=1" class="btn btn-small">🚪 登出</a>
                </div>
            </div>

            <div class="upload-area">
                <div class="upload-box" id="uploadBox">
                    <div class="upload-icon">📤</div>
                    <div class="upload-text">点击或拖拽文件到此处上传</div>
                    <div class="upload-hint">支持所有文件类型，最大 <?= MAX_FILE_SIZE / 1024 / 1024 ?>MB</div>
                    <div class="progress-bar" id="progressBar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    <input type="file" id="file-input" multiple>
                </div>
            </div>

            <div class="files-list">
                <div class="list-header">
                    <div class="list-title">文件列表</div>
                    <div style="color: #999; font-size: 14px;">共 <?= count($files) ?> 个文件</div>
                </div>

                <?php if (empty($files)): ?>
                    <div class="empty-state">
                        <div class="empty-state-icon">📂</div>
                        <div class="empty-state-text">暂无文件，上传第一个文件吧！</div>
                    </div>
                <?php else: ?>
                    <div class="files-grid">
                        <?php foreach ($files as $file): ?>
                            <div class="file-item">
                                <div class="file-icon"><?= getFileIcon($file['file_ext']) ?></div>
                                <div class="file-info">
                                    <div class="file-name" title="<?= htmlspecialchars($file['original_name']) ?>">
                                        <?= htmlspecialchars($file['original_name']) ?>
                                    </div>
                                    <div class="file-meta">
                                        <span><?= formatFileSize($file['file_size']) ?></span>
                                        <span><?= date('Y-m-d H:i', strtotime($file['upload_time'])) ?></span>
                                        <span>下载 <?= $file['download_count'] ?> 次</span>
                                    </div>
                                    <?php if (!empty($file['direct_link'])): ?>
                                        <div class="file-direct-link">
                                            <strong>直链：</strong>
                                            <a href="<?= getDirectLink($file['direct_link']) ?>" target="_blank">
                                                <?= getDirectLink($file['direct_link']) ?>
                                            </a>
                                            <button class="copy-btn" onclick="copyToClipboard('<?= getDirectLink($file['direct_link']) ?>', this)">复制</button>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="file-actions">
                                    <a href="file_settings.php?id=<?= $file['id'] ?>" class="btn btn-info btn-small">
                                        ⚙️ 设置
                                    </a>
                                    <a href="file.php?id=<?= $file['id'] ?>" class="btn btn-small" style="background: #5856D6; box-shadow: 0 2px 8px rgba(88, 86, 214, 0.2);" target="_blank">
                                        📄 文件页
                                    </a>
                                    <?php if (empty($file['direct_link'])): ?>
                                        <button class="btn btn-info btn-small" onclick="generateDirectLink(<?= $file['id'] ?>, this)">
                                            🔗 生成直链
                                        </button>
                                    <?php endif; ?>
                                    <button class="btn btn-success btn-small" onclick="downloadFile(<?= $file['id'] ?>)">
                                        ⬇️ 下载
                                    </button>
                                    <button class="btn btn-danger btn-small" onclick="showDeleteDialog(<?= $file['id'] ?>, '<?= htmlspecialchars($file['original_name']) ?>')">
                                        🗑️ 删除
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // CSRF令牌
        const csrfToken = '<?= $_SESSION['csrf_token'] ?>';

        <?php if ($isLoggedIn): ?>
        // 拖拽上传
        const uploadBox = document.getElementById('uploadBox');
        const fileInput = document.getElementById('file-input');
        const progressBar = document.getElementById('progressBar');
        const progressFill = document.getElementById('progressFill');

        uploadBox.addEventListener('click', () => fileInput.click());

        uploadBox.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadBox.classList.add('dragover');
        });

        uploadBox.addEventListener('dragleave', () => {
            uploadBox.classList.remove('dragover');
        });

        uploadBox.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadBox.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });

        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });

        function handleFiles(files) {
            if (files.length === 0) return;

            Array.from(files).forEach(file => uploadFile(file));
        }

        function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('csrf_token', csrfToken);

            progressBar.style.display = 'block';
            progressFill.style.width = '0%';

            const xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percent = (e.loaded / e.total) * 100;
                    progressFill.style.width = percent + '%';
                }
            });

            xhr.addEventListener('load', () => {
                progressBar.style.display = 'none';
                progressFill.style.width = '0%';

                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    // 显示上传成功信息
                    const directLink = response.data.direct_url;
                    const fileName = response.data.name;

                    let message = `文件 "${fileName}" 上传成功！\n\n`;
                    message += `删除码：使用管理员密码\n`;
                    message += `直链：${directLink}`;

                    alert(message);

                    setTimeout(() => window.location.reload(), 500);
                } else {
                    showToast(response.message, 'error');
                }
            });

            xhr.addEventListener('error', () => {
                progressBar.style.display = 'none';
                showToast('上传失败！', 'error');
            });

            xhr.open('POST', 'upload.php', true);
            xhr.send(formData);
        }

        function downloadFile(fileId) {
            window.location.href = 'download.php?id=' + fileId;
        }

        function showDeleteDialog(fileId, fileName) {
            if (confirm(`确定要删除文件 "${fileName}" 吗？\n此操作不可恢复！`)) {
                deleteFile(fileId);
            }
        }

        function deleteFile(fileId) {
            const password = prompt('请输入管理员密码：');
            if (password === null) return;

            const formData = new FormData();
            formData.append('id', fileId);
            formData.append('delete_code', password);
            formData.append('csrf_token', csrfToken);

            fetch('delete.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('删除成功！', 'success');
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    showToast(data.message, 'error');
                }
            })
            .catch(error => {
                showToast('删除失败！', 'error');
            });
        }

        function generateDirectLink(fileId, button) {
            const formData = new FormData();
            formData.append('id', fileId);
            formData.append('csrf_token', csrfToken);

            button.disabled = true;
            button.textContent = '生成中...';

            fetch('api.php?action=generate_link', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                button.disabled = false;
                if (data.success) {
                    showToast('直链生成成功！', 'success');
                    setTimeout(() => window.location.reload(), 1000);
                } else {
                    showToast(data.message, 'error');
                    button.textContent = '🔗 生成直链';
                }
            })
            .catch(error => {
                button.disabled = false;
                button.textContent = '🔗 生成直链';
                showToast('生成失败！', 'error');
            });
        }

        function copyToClipboard(text, button) {
            navigator.clipboard.writeText(text).then(() => {
                const originalText = button.textContent;
                button.textContent = '已复制';
                showToast('链接已复制到剪贴板', 'success');
                setTimeout(() => {
                    button.textContent = originalText;
                }, 2000);
            }).catch(() => {
                showToast('复制失败', 'error');
            });
        }
        <?php endif; ?>

        function showToast(message, type) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type;
            toast.classList.add('show');

            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html>
